import 'package:cached_network_image/cached_network_image.dart';
import 'package:syria_sports/data/apiClient/apis_data.dart';
import 'package:syria_sports/presentation/players/player_profile_screen/player_profile_screen.dart';
import 'package:syria_sports/widgets/screen_state_widget.dart';

import '../../../../core/network/internet_cubit.dart';
import '../../../../core/utils/show_toast.dart';
import '../../../../dialogs/add_note_bottom_sheet.dart';
import '../../../players/add_player_page/widgets/my_circle_avatar.dart';
import '../../../my_qr_code/bloc/my_qr_code_screen.dart';
import '../widgets/cp_loading_widget.dart';
import '../widgets/exercise_selection_widget.dart';
import 'cp_cubit.dart';
import 'package:flutter/material.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:flutter_analog_clock/flutter_analog_clock.dart';

class CPScreen extends StatelessWidget {
  const CPScreen({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
    Locale currentLocale = Localizations.localeOf(context);
    String formattedDate;
    String formattedTime;

    try {
      formattedDate = DateFormat('EEEE, d MMMM',currentLocale.languageCode).format(DateTime.now());
      formattedTime = DateFormat('HH:mm',currentLocale.languageCode).format(DateTime.now());
    } catch (e) {
      formattedDate = DateFormat('EEEE, d MMMM').format(DateTime.now());
      formattedTime = DateFormat('HH:mm, d MMMM').format(DateTime.now());
    }

    return Scaffold(
      body: BlocConsumer<CPCubit, CPState>(
        listener: (context, state) {
          // TODO: implement listener
        },
        builder: (context, state) {
          var cubit = CPCubit.get(context);
          APISData.cpCubit = cubit;

          return Container(
            height: height,
            width: width,
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(ImageConstant.imgBackground),
                fit: BoxFit.cover,
              ),
            ),
            child: Column(
              children: [
                BlocConsumer<InternetCubit,InternetState>(
                  listener: (context ,state){
                    if(state == InternetState.disconnected){
                      cubit.getOfflineHomeData();
                    }else{
                      cubit.getHomeData();
                    }
                  },
                  builder:(context , state)=> ListTile(
                    contentPadding: const EdgeInsets.only(bottom: 8,left: 4,right: 4),
                    leading: InkWell(
                      onTap: (){
                        Navigator.push(context, MaterialPageRoute(builder: (context) => PlayerProfileScreen.builder(context: context,index: -1)));
                      },
                      child: Hero(
                        tag: "player_selected-1",
                        child: MyCircleAvatar(
                          borderColor: Colors.red,
                          backgroundColor: theme.scaffoldBackgroundColor,
                          editMode: false,
                          borderSize: 1,
                          imageURL:PrefUtils.getImageLink(),
                          offline: InternetCubit.get(context).state != InternetState.connected,
                        ),
                      ),
                    ),
                    title: Text('اهلا ${PrefUtils.getFullName()}',style: theme.textTheme.titleMedium),
                    subtitle: Text(formattedDate),
                    trailing: InkWell(
                      onTap: (){
                        Navigator.push(context, MaterialPageRoute(builder: (context) => MyQrCodeScreen(code: PrefUtils.getBarcode(),)));
                      },
                      child: CustomImageView(
                        height: 100,
                        fit: BoxFit.fitHeight,
                        imagePath: ImageConstant.imgLogo,
                      ),
                    ),
                  ),
                ),
                Expanded(
                  child:ScreenStateWidget(
                    isLoading: state is CPLoading || InternetCubit.get(context).state == InternetState.loading,
                    isDone: state is CPDone,
                    isError: state is CPError,
                    onLoading: const CPLoadingWidget(),
                    onRefresh:() async{
                      cubit.init(InternetCubit.get(context).state == InternetState.connected);
                    },
                    onDone:(state is! CPDone)?const SizedBox() : SizedBox(
                      height: height,
                      child: SingleChildScrollView(
                        physics: const AlwaysScrollableScrollPhysics(),
                        child: Column(
                          mainAxisSize: MainAxisSize.max,
                          children: [
                            if(cubit.homeData.gym.isEmpty || cubit.homeData.gym.isEmpty)
                              Container(
                                margin:const EdgeInsets.symmetric(vertical: 4,horizontal: 8),
                                clipBehavior: Clip.antiAlias,
                                height: 200,
                                decoration: BoxDecoration(
                                    color: Colors.white24,
                                    image: DecorationImage(
                                      image:Image.asset(ImageConstant.imgLogo).image,
                                    )
                                ),
                                child: Container(
                                  padding:const EdgeInsets.all(4),
                                  decoration: const BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter,
                                      colors: [
                                        Colors.black26,
                                        Colors.transparent,
                                        Colors.transparent,
                                        Colors.black26,
                                      ],
                                    ),
                                  ),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text('تسجيل حضور يومي', style: theme.textTheme.titleMedium!.copyWith(color: Colors.red),),
                                          CircleAvatar(
                                            backgroundColor: Colors.white70,
                                            child: IconButton(
                                              icon: CustomImageView(
                                                color:Colors.red,
                                                imagePath: ImageConstant.imgArrowLeft,
                                              ),
                                              onPressed: (){
                                                showDialog(
                                                  context: context,
                                                  builder: (BuildContext context) {
                                                    return AlertDialog(
                                                      shadowColor: Colors.grey,
                                                      elevation: 16,
                                                      backgroundColor: Theme.of(context).colorScheme.secondary,
                                                      title: Text('اختر تمرين',style: theme.textTheme.titleMedium,),
                                                      content: ExerciseSelectionWidget(
                                                        gyms: cubit.homeData.gyms,
                                                        onExerciseSelected: (value){
                                                          cubit.selectExercise(value.exerciseId);
                                                          Navigator.pop(context);
                                                        },
                                                      ),
                                                    );
                                                  },
                                                );
                                              },
                                            ),
                                          )
                                        ],
                                      ),
                                      Align(
                                        alignment: Alignment.centerRight,
                                        child: Text('', style: theme.textTheme.titleSmall,),
                                      ),
                                    ],
                                  ),
                                ),
                              )
                            else
                              Container(
                                height: 200,
                                margin:const EdgeInsets.symmetric(vertical: 4,horizontal: 8),
                                clipBehavior: Clip.antiAlias,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.circular(8),
                                    color: Theme.of(context).colorScheme.secondary,
                                    image: DecorationImage(
                                      fit:(cubit.homeData.gym.first.image== null )?null: BoxFit.cover,
                                      image:(cubit.homeData.gym.first.image== null )?Image.asset(ImageConstant.imgLogo).image :CachedNetworkImageProvider(cubit.homeData.gym.first.image!),
                                    )
                                ),
                                child: Container(
                                  padding:const EdgeInsets.all(4),
                                  decoration: BoxDecoration(
                                    gradient: LinearGradient(
                                      begin: Alignment.topCenter,
                                      end: Alignment.bottomCenter,
                                      colors: [
                                        Colors.black,
                                        Colors.black.withOpacity(0),
                                        Colors.black.withOpacity(0),
                                        Colors.black,
                                      ],
                                    ),
                                  ),
                                  child: Column(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    children: [
                                      Row(
                                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                        children: [
                                          Text(cubit.homeData.gym.first.name, style: theme.textTheme.titleMedium!.copyWith(color: Colors.deepOrange),),
                                          CircleAvatar(
                                            backgroundColor: Colors.white38,
                                            radius: 22.fSize,
                                            child: IconButton(
                                              icon: CustomImageView(
                                                color:Colors.red.withOpacity(.7),
                                                imagePath: ImageConstant.imgArrowLeft,
                                              ),
                                              onPressed: (){
                                                showDialog(
                                                  context: context,
                                                  builder: (BuildContext context) {
                                                    return AlertDialog(
                                                      shadowColor: Colors.grey,
                                                      elevation: 16,
                                                      backgroundColor: Theme.of(context).colorScheme.secondary,
                                                      title: Text('اختر تمرين',style: theme.textTheme.titleMedium,),
                                                      content: ExerciseSelectionWidget(
                                                        gyms: cubit.homeData.gyms,
                                                        onExerciseSelected: (value){
                                                          cubit.selectExercise(value.exerciseId);
                                                          Navigator.pop(context);
                                                        },
                                                      ),
                                                    );
                                                  },
                                                );
                                              },
                                            ),
                                          )
                                        ],
                                      ),
                                      Align(
                                        alignment: Alignment.centerRight,
                                        child: Text(cubit.homeData.exercise.first.name, style: theme.textTheme.titleSmall?.copyWith(color: Colors.white),),
                                      ),
                                    ],
                                  ),
                                ),
                              ),
                            Row(
                              children: [
                                Expanded(
                                  flex: 2,
                                  child: Padding(
                                    padding: const EdgeInsets.symmetric(horizontal: 4.0),
                                    child: Card(
                                      color: Theme.of(context).colorScheme.secondary,
                                      child: SizedBox(
                                        height: 150,
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          crossAxisAlignment: CrossAxisAlignment.start,
                                          children: [
                                            Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                              children: [
                                                Text(
                                                    'الحضور',
                                                    style: theme.textTheme.titleLarge
                                                ),
                                                CustomImageView(
                                                  imagePath: ImageConstant.imgPlayerGym,
                                                  height: 32.adaptSize,
                                                  width: 32.adaptSize,
                                                ),
                                              ],
                                            ),
                                            Row(
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                              children: [
                                                Padding(
                                                  padding: const EdgeInsets.all(8.0),
                                                  child: Column(
                                                    children: [
                                                      Text(
                                                          cubit.homeData.attendanceCount,
                                                          style: const TextStyle(
                                                              color: Colors.deepOrange,
                                                              fontSize: 32
                                                          )
                                                      ),
                                                      Text(
                                                          'متدرب',
                                                          style: theme.textTheme.titleMedium
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                                IconButton(
                                                  onPressed: (){
                                                    //if(kDebugMode) {
                                                    if(APISData.homeData.exercise.isNotEmpty) {
                                                      showAddNoteBottomSheet(context ,APISData.homeData.exercise.first );
                                                      /*showDialog(
                                                              context: context,
                                                              builder: (BuildContext context) {
                                                                return AddNoteDialog(gymExercise:APISData.homeData.exercise.first ,);
                                                              },
                                                            );*/
                                                    } else{
                                                      showErrorMessage(message: 'الرجاء تحديد تمرين اولاً');
                                                    }
                                                    /*}else{
                                                          showMessage('هذه الخدمة غير متاحة في الاصدار التجريبي');
                                                        }*/
                                                  },
                                                  icon: CustomImageView(
                                                    imagePath: ImageConstant.icNoteAdd,
                                                    color: Colors.deepOrange,
                                                    height: 32.adaptSize,
                                                    width: 32.adaptSize,
                                                  ),
                                                ),
                                              ],
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                                Expanded(
                                  flex: 2,
                                  child: Card(
                                    color: Theme.of(context).colorScheme.secondary,
                                    child: Container(
                                      height: 150,
                                      padding:const EdgeInsets.all(4),
                                      child: AnalogClock.dark(dialColor: Theme.of(context).colorScheme.onPrimaryContainer),
                                    ),
                                  ),
                                ),
                                // Card(),
                              ],
                            ),

                            Padding(
                              padding: const EdgeInsets.symmetric(vertical: 0.0,horizontal: 8),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text('اليوم:',style: theme.textTheme.titleMedium),
                                  TextButton(
                                      onPressed: (){},
                                      child: Text('',style: theme.textTheme.titleSmall))
                                ],
                              ),
                            ),
                            Column(
                              children:List.generate(cubit.homeData.attendanceData.length, (index) => Card(
                                color: Theme.of(context).colorScheme.secondary,
                                child: Padding(
                                  padding: const EdgeInsets.all(8.0),
                                  child: InkWell(
                                    onTap: () {
                                      Navigator.push(
                                        context,
                                        MaterialPageRoute(
                                          builder: (context) => PlayerProfileScreen.builder(
                                            context: context,
                                            index: index,
                                            user: cubit.homeData.attendanceData[index].user,
                                          ),
                                        ),
                                      );
                                    },
                                    child: Row(
                                      crossAxisAlignment: CrossAxisAlignment.center,
                                      children: [
                                        Hero(
                                          tag: "player_selected$index",
                                          child: MyCircleAvatar(
                                            borderColor: Colors.red,
                                            backgroundColor: Theme.of(context).colorScheme.onPrimaryContainer,
                                            editMode: false,
                                            width: 38,
                                            activeIconWidth: 22,
                                            imageURL: cubit.homeData.attendanceData[index].user.image,
                                            active: cubit.homeData.attendanceData[index].user.activeValue == '1',
                                          ),
                                        ),
                                        const SizedBox(width: 8), // مسافة أفقية بين العناصر
                                        Expanded(
                                          child: Column(
                                            crossAxisAlignment: CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                cubit.homeData.attendanceData[index].user.fullName,
                                                style: theme.textTheme.titleMedium,
                                              ),
                                              const SizedBox(height: 8),
                                              Text(
                                                'المستوى ${cubit.homeData.attendanceData[index].user.level}',
                                                style: CustomTextStyles.bodySmall10,
                                              ),
                                              Text(
                                                'الساعة: ${cubit.homeData.attendanceData[index].datetime.hour}:${cubit.homeData.attendanceData[index].datetime.minute}',
                                                style: CustomTextStyles.bodySmallOnPrimary,
                                              ),
                                            ],
                                          ),
                                        ),
                                        CustomImageView(
                                          imagePath: ImageConstant.imgArrowLeftBlueGray300,
                                          height: 32.adaptSize,
                                          width: 32.adaptSize,
                                        ),
                                      ],
                                    ),
                                  ),
                                ),
                              )),
                            ),
                            const SizedBox(height: 32),
                          ],
                        ),
                      ),
                    ),
                    ),
                  ),
              ],
            ),
          );
        },
      ),
    );
  }
}
